package com.astrob.activitys;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import com.astrob.mapsforge.MapsForgeTileSource;
import com.astrob.nhcmap.R;

import org.mapsforge.core.graphics.Bitmap;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.MapPosition;
import org.mapsforge.core.model.Tag;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.util.AndroidPreferences;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.datastore.PointOfInterest;
import org.mapsforge.map.layer.GroupLayer;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.hills.HillsRenderConfig;
import org.mapsforge.map.layer.hills.MemoryCachingHgtReaderTileSource;
import org.mapsforge.map.layer.hills.SimpleShadingAlgorithm;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.common.PreferencesFacade;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleMenu;
import org.osmdroid.views.MapView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


//http://www.tuicool.com/articles/Rr2qAbn

public class MapsforgeActivity extends Activity {

    public static Intent createIntent(Context context) {
        return new Intent(context, MapsforgeActivity.class);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapsforge_activity);
        intMapsforge();
    }

    private org.mapsforge.map.android.view.MapView mapView = null;
    private PreferencesFacade preferencesFacade;
    private XmlRenderThemeStyleMenu renderThemeStyleMenu;
    private List<TileCache> tileCaches = new ArrayList<TileCache>();

    private String getPersistableId() {
//        return "OSMActivity";
        return this.getClass().getSimpleName();
    }

    private float getScreenRatio() {
        return 1.0f;//dp:px
    }

    private MapDataStore getMapFile() {
        String mapdir = Environment.getExternalStorageDirectory() + "/BHCMapper/mapsforge";
        return new MapFile(new File(mapdir, "china.map"));
    }

    private XmlRenderTheme getRenderTheme() {
        return InternalRenderTheme.DEFAULT;
    }

    private HillsRenderConfig hillsConfig = null;

    private HillsRenderConfig getHillsRenderConfig() {
        File demFolder = new File(Environment.getExternalStorageDirectory() + "/BHCMapper/", "dem");
        if (!(demFolder.exists() && demFolder.isDirectory() && demFolder.canRead() && demFolder.listFiles().length > 0)) {
            hillsConfig = null;
        } else {
            // minimum setup for hillshading
            MemoryCachingHgtReaderTileSource hillTileSource = new MemoryCachingHgtReaderTileSource(demFolder, new SimpleShadingAlgorithm(), AndroidGraphicFactory.INSTANCE);
            hillTileSource.setEnableInterpolationOverlap(false);
            hillsConfig = new HillsRenderConfig(hillTileSource);

            // call after setting/changing parameters, walks filesystem for DEM metadata
            hillsConfig.indexOnThread();
        }
        return hillsConfig;
    }

    private byte getZoomLevelMin() {
        return (byte) 0;
    }

    /**
     * @return the maximum zoom level of the map view.
     */
    private byte getZoomLevelMax() {
        return (byte) 24;
    }

    private void intMapsforge() {
        mapView = (org.mapsforge.map.android.view.MapView) findViewById(R.id.id_mapViewM);
        mapView.setVisibility(View.VISIBLE);
        //createSharedPreferences
//        MapsForgeTileSource.createInstance(getApplication());

        preferencesFacade = new AndroidPreferences(this.getSharedPreferences(getPersistableId(), MODE_PRIVATE));

        //createMapViews
        Parameters.FRAME_BUFFER_HA2 = true;

        mapView.getModel().init(preferencesFacade);//设置MapPosition
        mapView.setClickable(true);
        mapView.getMapScaleBar().setVisible(true);
        mapView.setBuiltInZoomControls(true);
        mapView.getMapZoomControls().setAutoHide(true);
        mapView.getMapZoomControls().setZoomLevelMin(getZoomLevelMin());
        mapView.getMapZoomControls().setZoomLevelMax(getZoomLevelMax());

//        mapView.getMapZoomControls().setZoomControlsOrientation(MapZoomControls.Orientation.VERTICAL_IN_OUT);
//        mapView.getMapZoomControls().setZoomInResource(R.drawable.zoom_control_in);
//        mapView.getMapZoomControls().setZoomOutResource(R.drawable.zoom_control_out);
//        mapView.getMapZoomControls().setMarginHorizontal(getResources().getDimensionPixelOffset(R.dimen.controls_margin));
//        mapView.getMapZoomControls().setMarginVertical(getResources().getDimensionPixelOffset(R.dimen.controls_margin));


        //createTileCaches
        tileCaches.add(AndroidUtil.createTileCache(this, getPersistableId(),
                mapView.getModel().displayModel.getTileSize(), getScreenRatio(),
                mapView.getModel().frameBufferModel.getOverdrawFactor(), true));

        TileCache tileCache = tileCaches.get(0);
        //createLayers
        TileRendererLayer tileRendererLayer = AndroidUtil.createTileRendererLayer(tileCache,
                mapView.getModel().mapViewPosition, getMapFile(), getRenderTheme(), false, true, false,
                getHillsRenderConfig());
        mapView.getLayerManager().getLayers().add(tileRendererLayer);

        //可以混合加入瓦片图，多图层

        //createControls 设置MapPosition
        mapView.getModel().mapViewPosition.setCenter(new LatLong(32.0607297590, 118.7629586387));
        mapView.getModel().mapViewPosition.setZoomLevel((byte) 16);


    }

    private GroupLayer groupLayer = null;

    private void addOverLays() {
        // Clear overlays
        if (groupLayer != null) {
            mapView.getLayerManager().getLayers().remove(groupLayer);
        } else {
            groupLayer = new GroupLayer();
        }

        Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(getResources().getDrawable(R.drawable.center_marker));
        LatLong pt = new LatLong(32.0607297590, 118.7629586387);
        Tag tag = new Tag("name", "家乐福");
        List<Tag> tags = new ArrayList<>();
        tags.add(tag);
        PointOfInterest pointOfInterest = new PointOfInterest((byte) 5, tags, pt);

        org.mapsforge.map.layer.overlay.Marker marker = new MarkerImpl(pt, bitmap, 0, -bitmap.getHeight() / 2, pointOfInterest);
        groupLayer.layers.add(marker);
        mapView.getLayerManager().getLayers().add(groupLayer);
        mapView.getLayerManager().redrawLayers();
    }

    private class MarkerImpl extends org.mapsforge.map.layer.overlay.Marker {
        private final PointOfInterest pointOfInterest;

        private MarkerImpl(LatLong latLong, Bitmap bitmap, int horizontalOffset, int verticalOffset, PointOfInterest pointOfInterest) {
            super(latLong, bitmap, horizontalOffset, verticalOffset);
            this.pointOfInterest = pointOfInterest;
        }

        @Override
        public boolean onTap(LatLong tapLatLong, org.mapsforge.core.model.Point layerXY, org.mapsforge.core.model.Point tapXY) {
            // GroupLayer does not have a position, layerXY is null
            layerXY = mapView.getMapViewProjection().toPixels(getPosition());
            if (contains(layerXY, tapXY)) {
                Toast.makeText(MapsforgeActivity.this, pointOfInterest.tags.get(0).value, Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    }

    private void updateMap() {
        mapView.getLayerManager().redrawLayers();
    }

    //save MapPosition
    private void save() {
        mapView.getModel().save(preferencesFacade);
        preferencesFacade.save();
    }

    private void destroyMap() {
        AndroidGraphicFactory.clearResourceMemoryCache();
        tileCaches.clear();
    }

//    mapView.getModel().mapViewPosition.zoomIn();
//    mapView.getModel().mapViewPosition.zoomOut();


//    AndroidTileBitmap bmp = (AndroidTileBitmap) renderer.executeJob(mapGeneratorJob);
//
//    public TileBitmap executeJob(RendererJob rendererJob) {
//
//
////Draw the tile---colin--画矢量图
//protected void compileRenderTheme() {
//    this.renderThemeFuture = new RenderThemeFuture(this.graphicFactory, this.xmlRenderTheme, this.displayModel);
//    new Thread(this.renderThemeFuture).start();
//}



}
